package com.securityLearn.sessionAuth.config.interceptor;


import com.securityLearn.sessionAuth.entity.UserDto;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 授权拦截器
 * 1、校验用户是否登录
 * 2、校验用户是否拥有操作权限
 *
 * @author duzq
 * @date 2021-8-26 21:32:28
 */
@Component
public class SimpleAuthenticationInterceptor implements HandlerInterceptor {

    /**
     * 请求拦截方法
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //读取会话信息
        Object object = request.getSession().getAttribute(UserDto.SESSION_USER_KEY);
        if (object == null) {
            writeContent(response, "请登录");
        }
        UserDto user = (UserDto) object;
        //请求的url
        String requestURI = request.getRequestURI();
        if (user.getAuthorities().contains("p1") && requestURI.contains("/r1")) {
            return true;
        }
        if (user.getAuthorities().contains("p2") && requestURI.contains("/r2")) {
            return true;
        }
        writeContent(response, "权限不足，拒绝访问");
        return false;
    }

    /**
     * 响应输出
     * @param response
     * @param msg
     * @throws IOException
     */
    private void writeContent(HttpServletResponse response, String msg) throws IOException {
        // response.setContentType("text/html;charset=utf-8");
        // PrintWriter writer = response.getWriter();
        // writer.print(msg);
        // writer.close();
        // response.resetBuffer();
        throw new RuntimeException("权限拦截：" + msg);
    }
}
